<template>
	<div style="position: relative;width: 100%;">
		<script :id="id" type="text/plain"></script>
	</div>
</template>
<script type="text/javascript">
import { extend, each, uuid } from '../../utils';
import axios from 'axios';

//解决跨域认证信息问题
window.UE.utils.isCrossDomainUrl = function() {
	return false;
}
const defaultAjaxOptions = {
    method:"POST",
    data: {},//需要传递对象的话只能覆盖
    onsuccess:function() {
    },
    onerror:function() {
    }
};
//解决接口跨域问题
window.UE.ajax.request = function(url, ajaxOptions) {
	if (typeof url === "object") {
        ajaxOptions = url;
        url = ajaxOptions.url;
    }
    var ajaxOpts = ajaxOptions ? extend({}, defaultAjaxOptions, ajaxOptions) : extend({}, defaultAjaxOptions);
    var paramsStr = JSON.stringify(ajaxOpts);
    var params = JSON.parse(paramsStr);
    extend(params, params.data);
    delete params.data;
    var method = ajaxOpts.method.toUpperCase();
    if (method == "POST") {
    	axios.post(url, params).then((response) => {
    		ajaxOpts.onsuccess(response.request);
    	}).catch((error) => {
    		if(error.response) {
    			ajaxOpts.onerror(error.response.request);	
    		}
    	});
    } else {
    	axios.get(url, {params}).then((response) => {
	    	ajaxOpts.onsuccess(response.request);
    	}).catch((error) => {
    		if(error.response) {
    			ajaxOpts.onerror(error.response.request);	
    		}
    	});
    }
}

const triggerEvent = function(element, name) {
	var event = document.createEvent('Event');
	// 初始化一个点击事件，可以冒泡，无法被取消
	event.initEvent(name, true, false);
	if(element.fireEvent) {
		element.fireEvent(event);
	} else {
		element.dispatchEvent(event);
	}
}

//解决单个上传图片跨域问题
const afterConfigReady = UE.Editor.prototype.afterConfigReady;
window.UE.Editor.prototype.afterConfigReady = function(handler) {
	afterConfigReady.call(this, function() {
		handler.apply(this, arguments);
		const iframes = document.getElementsByTagName("iframe");
		each(iframes, function() {
			if(this.style.cursor == 'pointer') {
				const doc = this.contentDocument || this.contentWindow.document;
				if(doc.querySelectorAll) {
					const forms = doc.querySelectorAll("[id^=edui_form_]");
					if(forms && forms.length) {
						var form = forms[0];
						var iframe = doc.querySelectorAll("[id^=edui_iframe_]")[0];	
						var input = doc.querySelectorAll("[id^=edui_input_]")[0];
						form.submit = function() {
							var action = this.action;
							var name = input.name;
							var file = input.files[0];
							var params = {};
							params[name] = file;
							axios.post(action, params, {
								headers: {
									"Content-Type": "multipart/form-data"
								}
							}).then((response) => {
								var body = (iframe.contentDocument || iframe.contentWindow.document).body;
								body.innerText = response.request.responseText;
								triggerEvent(iframe, 'load');
							}).catch((error) => {
					    		triggerEvent(iframe, 'load');
					    	});
							return false;
						}
					}
				}
			}
		});
	});
}

export default {
	props: {
		value: {
			type: String,
			default: ''
		},
		config: {
			type: Object,
			default() {
				return {};
			}
		},
		id: {
			type: String,
			default() {
				return `ueditor_${uuid()}`;
			}
		}
	},
	data() {
		return {
			ready: false,
			content: this.value
		};
	},
	methods: {
		onReady(ue) {
			ue.setContent(this.content);
			if(!this.ready) {
				this.ready = true;
				this.$emit("ready", ue);
			}
		}
	},
	mounted() {
		this.$nextTick(() => {
			const ue = window.UE.getEditor(this.id, this.config);
			ue.ready(() => {
				this.onReady(ue);
			});
			ue.addListener("contentChange", (e) => {
				this.$emit('input', ue.getContent());
				this.content = ue.getContent();
			});
		});
	},
	beforeDestroy() {
		const ue = window.UE.getEditor(this.id);
		if(ue) {
			ue.destroy();
		}
	}

}
</script>